// import { base64ToPath } from 'image-tools'
let downloadFile_onoff = true
//下载文件 传入地址
function file(fileUrl) {
	if (downloadFile_onoff) {
		downloadFile_onoff = false
		uni.showLoading({
			title: '打开中请稍后...'
		});
		//文件下载
		uni.downloadFile({
			url: fileUrl,
			success: function(res) {
				// console.log('下载成功')
				console.log(res);
				var filePath = res.tempFilePath;
				// 打开文件有效值 doc, xls, ppt, pdf, docx, xlsx, pptx
				uni.openDocument({
					filePath: filePath,
					success: function(res) {
						uni.hideLoading();
						downloadFile_onoff = true;
					},
					fail() {
						uni.showToast({
							title: '暂不支持此类型',
							duration: 2000
						});
						uni.hideLoading();
						downloadFile_onoff = true;
					}
				});
			},
			fail(err) {
				uni.hideLoading();
				uni.showToast({
					icon:"none",
					title: err.errMsg,
					duration: 2000
				});
			}
		});
	}
}

//保存
function save(data, urlKey,token) {
	var src = data[urlKey]+`?Authorization=${token}&us=app`
	//#ifdef MP-WEIXIN
	//提前向用户发起授权请求
	uni.authorize({
		scope: 'scope.writePhotosAlbum',
		success() {
			console.log('kxj-previewImage:允许储存');
			downloadImg(src);
		}
	});
	//#endif

	//#ifdef APP-PLUS
	downloadImg(src);
	//#endif

	//#ifdef H5
	//非同源图片将直接打开
	var abtn = document.createElement('a');
	abtn.href = src;
	abtn.download = '';
	abtn.target = '_blank';
	abtn.click();
	//#endif
}
//下载并保存文件
function downloadImg(src) {
	//下载图片文件
	uni.showLoading({
		title: '保存系统相册中'
	});
	uni.downloadFile({
		url: src,
		success: function(res) {
			uni.hideLoading();
			uni.saveImageToPhotosAlbum({
				filePath: res.tempFilePath,
				success: () => {
					uni.showToast({
						title: '已保存至相册',
						duration: 1000
					});
				},
				fail: (err) => {
					uni.showToast({
						title: '保存失败：' + err.code,
						icon: "none"
					});
				}
			});
		},
		fail: function() {
			uni.hideLoading();
			uni.showToast({
				title: '图片下载失败',
				icon: 'none',
				duration: 1000
			});
		}
	});
}
function qssSave(base64){
	base64ToPath(base64).then(path => {
		// 预览图片
		uni.previewImage({
			urls:[path],
			current:0,
			longPressActions: {
				itemList: ['保存图片'],
				success: function(data) {
					//下载图片文件
					uni.showLoading({
						title: '保存系统相册中'
					});
					uni.saveImageToPhotosAlbum({
						filePath: path,
						success: () => {
							uni.hideLoading();
							uni.showToast({
								title: '已保存至相册',
								duration: 1000
							});
						},
						fail: (err) => {
							uni.hideLoading();
							uni.showToast({
								title: '保存失败：' + err.code,
								icon: "none"
							});
						}
					});
				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			}
		});
	}).catch(error => {
		console.error(error)
	})
}

module.exports = {
	file,
	save,
	qssSave
}
